//
//  ViewController.m
//  AVPlayerDemo
//
//  Created by CaoJie on 14-5-5.
//  Copyright (c) 2014年 yiban. All rights reserved.
//

#import "YXMusicPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AFNetworking/AFNetworking.h>
#import "YXMusicModel.h"
#import "AppDelegate.h"
#import "PlayerView.h"

@interface YXMusicPlayerViewController () {
    BOOL _played;
   // NSString *_totalTime;
    NSDateFormatter *_dateFormatter;
}
@property (weak, nonatomic) IBOutlet UIImageView *musicImage;

@property(nonatomic,copy)NSString *totalTime;
@property (weak, nonatomic) IBOutlet UILabel *musicNameLabel;
@property(nonatomic,strong)NSMutableArray *songsArray;
@property(nonatomic,strong)NSURL *tempUrl;
@property(nonatomic,assign)NSInteger currentIndex;

@property (nonatomic ,weak) IBOutlet PlayerView *playerView;
@property (nonatomic ,strong) AVPlayer *player;
@property (nonatomic ,strong) AVPlayerItem *playerItem;


@property (nonatomic ,weak) IBOutlet UIButton *stateButton;
@property (nonatomic ,weak) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (nonatomic ,strong) id playbackTimeObserver;

@property (nonatomic ,weak) IBOutlet UISlider *videoSlider;
@property (nonatomic ,weak) IBOutlet UIProgressView *videoProgress;
//播放模式 0:顺序  1:随机   2: 单曲循环
@property(nonatomic,assign)int playModel;

@property(nonatomic,strong)AppDelegate *app;

@property(nonatomic,strong)NSTimer *timer;

-(IBAction)stateButtonTouched:(id)sender;

-(IBAction)videoSlierChangeValue:(id)sender;
-(IBAction)videoSlierChangeValueEnd:(id)sender;

@end

@implementation YXMusicPlayerViewController
//-(AVPlayer *)player {
//    if (_player == nil) {
//        _player = [[AVPlayer alloc]init];
//    }
//    return _player;
//}

-(NSMutableArray *)songsArray {
    if (_songsArray == nil) {
        _songsArray = [NSMutableArray array];
        _songsArray = self.app.musicArray;
    }
    return _songsArray;
}

-(AppDelegate *)app{
    if (_app == nil) {
        _app = [AppDelegate shareDelagate];
    }
    return _app;
}

- (void)viewDidLoad
{
[super viewDidLoad];
//    if (self.currentIndex != self.app.currentIndex) {
    
//    [self.timer invalidate];
//    self.timer = nil;
//    [self removeSave];
    
    self.currentIndex = self.app.currentIndex;
    [self starSongs];
    [self rotationAnimation];
      //雪花飘
   
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(snow) userInfo:nil repeats:YES];
//    }else{
//        NSLog(@"tttttt");
//    }
}
-(void)starSongs{
    self.app.currentIndex = self.currentIndex;
    if (self.songsArray.count >0) {
        YXMusicModel *musicModel = self.songsArray[self.currentIndex];
        self.tempUrl = [NSURL URLWithString:musicModel.playurl64];
        self.musicImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: musicModel.coverlarge]]];
//        [self rotationAnimation];
        self.musicNameLabel.text = musicModel.title;
    }else{
        self.tempUrl = [NSURL URLWithString:@"http://fdfs.xmcdn.com/group3/M02/70/FB/wKgDsVKGAO-ByTmeABwVN1LvPeQ356.mp3"];
    }
    
   // NSURL *videoUrl = self.tempUrl;
   NSURL *videoUrl = [NSURL URLWithString:@"http://v.jxvdy.com/sendfile/w5bgP3A8JgiQQo5l0hvoNGE2H16WbN09X-ONHPq3P3C1BISgf7C-qVs6_c8oaw3zKScO78I--b0BGFBRxlpw13sf2e54QA"];
    self.playerItem = [AVPlayerItem playerItemWithURL:videoUrl];
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    self.playerView.player = _player;
    self.stateButton.enabled = NO;

    // 添加播放结束通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
   [self stateMusic];
  //  self.app.player = self.player;
}

-(void)rotationAnimation{
    CALayer *layer = [[CALayer alloc]init];
    layer = self.musicImage.layer;
    layer.position = CGPointZero;
    layer.cornerRadius = 100;
    layer.masksToBounds = YES;
    [self.view.layer addSublayer:layer];
    
    CABasicAnimation *baseAnimation = [[CABasicAnimation alloc] init];
    baseAnimation.keyPath = @"transform.rotation"; // keyPath就是layer的属性
    baseAnimation.toValue = @(M_PI * 2);
     baseAnimation.duration = 30.0;
    baseAnimation.repeatCount = MAXFLOAT;
    // 控制layer停止动画的属性 假动画
    baseAnimation.removedOnCompletion = NO;
    baseAnimation.fillMode = kCAFillModeForwards;
    [self.musicImage.layer addAnimation:baseAnimation forKey:nil];
}

//雪花
-(void)snow
{  static int count = 0 ;
    count ++;
    
    CGFloat red= (random()%10)/10.0;
    CGFloat green= (random()%10)/10.0;
    CGFloat blue= (random()%10)/10.0;
   
    if (count % 10 == 0) {
        self.musicNameLabel.textColor = [UIColor colorWithRed:red green:green blue:blue alpha:1];
     }
    
    int startX= random()%414;
    int endX= random()%414;
    int width= random()%25;
    CGFloat time= (random()%100)/10+5;
    CGFloat alp= (random()%9)/10.0+0.1;
    
   
    UIImage* image= [UIImage imageNamed:@"snow.png"];
    UIImageView* imageView = [[UIImageView alloc] initWithImage:image];
    //    imageView.backgroundColor= [UIColor colorWithRed:red green:green blue:blue alpha:1];
    imageView.frame= CGRectMake(startX,-1*width,width,width);
    imageView.alpha=alp;
    
    [self.view addSubview:imageView];
    
    
    [UIView beginAnimations:nil context:(__bridge void * _Nullable)(imageView)];
    [UIView setAnimationDuration:time];
    
//    if(endX>50&&endX<270)
//    {
//        imageView.frame= CGRectMake(endX, 500-width/2, width, width);
//        
//    }
//    else if((endX>10&&endX<50)||(endX>300&&endX<350))
//        imageView.frame= CGRectMake(endX, 500-width/2, width, width);
//    else
        imageView.frame= CGRectMake(endX, 600, width, width);
    [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
    
    
}
-(void)onAnimationComplete:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context
{
    UIImageView* snowView = (__bridge UIImageView *)(context);
    [snowView removeFromSuperview];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
    
    __weak typeof(self) weakSelf = self;
    self.playbackTimeObserver = [self.playerView.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
        [weakSelf.videoSlider setValue:currentSecond animated:YES];
        NSString *timeString = [weakSelf convertTime:currentSecond];
       // NSLog(@"0000%@",timeString);
        weakSelf.timeLabel.text = [NSString stringWithFormat:@"%@",weakSelf.totalTime];
        weakSelf.currentTimeLabel.text = [NSString stringWithFormat:@"%@",timeString];
    }];
}

// KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
           // NSLog(@"AVPlayerStatusReadyToPlay");
            self.stateButton.enabled = YES;
            CMTime duration = self.playerItem.duration;// 获取音频总长度
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
            self.totalTime = [self convertTime:totalSecond];// 转换成播放时间
            [self customVideoSlider:duration];// 自定义UISlider外观
          //  NSLog(@"movie total duration:%f",CMTimeGetSeconds(duration));
            [self monitoringPlayback:self.playerItem];// 监听播放状态
        } else if ([playerItem status] == AVPlayerStatusFailed) {
           // NSLog(@"AVPlayerStatusFailed");
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
       // NSLog(@"Time Interval:%f",timeInterval);
        CMTime duration = _playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
    }
}

- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.playerView.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

- (void)customVideoSlider:(CMTime)duration {
    self.videoSlider.maximumValue = CMTimeGetSeconds(duration);
    UIGraphicsBeginImageContextWithOptions((CGSize){ 1, 1 }, NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [self.videoSlider setMinimumTrackImage:transparentImage forState:UIControlStateSelected];
    [self.videoSlider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
}

- (IBAction)stateButtonTouched:(id)sender {
    [self stateMusic];
}
//开始播放 ****
-(void)stateMusic{
    if (!_played) {
        [self.playerView.player play];
        [self.stateButton setTitle:@"Stop" forState:UIControlStateNormal];
    } else {
        [self.playerView.player pause];
        [self.stateButton setTitle:@"Play" forState:UIControlStateNormal];
    }
    _played = !_played;
}
- (IBAction)videoSlierChangeValue:(id)sender {
    UISlider *slider = (UISlider *)sender;
   // NSLog(@"value change:%f",slider.value);
    
    if (slider.value == 0.000000) {
        __weak typeof(self) weakSelf = self;
        [self.playerView.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
            [weakSelf.playerView.player play];
        }];
    }
}

- (IBAction)videoSlierChangeValueEnd:(id)sender {
    UISlider *slider = (UISlider *)sender;
    //NSLog(@"value end:%f",slider.value);
    CMTime changedTime = CMTimeMakeWithSeconds(slider.value, 1);
    
    __weak typeof(self) weakSelf = self;
    [self.playerView.player seekToTime:changedTime completionHandler:^(BOOL finished) {
        [weakSelf.playerView.player play];
        [weakSelf.stateButton setTitle:@"Stop" forState:UIControlStateNormal];
    }];
   
}

- (void)updateVideoSlider:(CGFloat)currentSecond {
    [self.videoSlider setValue:currentSecond animated:YES];
}


- (void)moviePlayDidEnd:(NSNotification *)notification {
   
   // NSLog(@"Play end");
    
    
    __weak typeof(self) weakSelf = self;
    [self.playerView.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
        [weakSelf.videoSlider setValue:0.0 animated:YES];
        [weakSelf.stateButton setTitle:@"Play" forState:UIControlStateNormal];
   }];
    
    [self removeSave];
    
    switch (self.playModel) {
        case 0:
            self.currentIndex++;
            if (self.currentIndex >= (int)self.songsArray.count) {
                self.currentIndex = 0;
            }
            break;
        case 1:
            self.currentIndex = arc4random_uniform((int)self.songsArray.count);
            break;
        case 2:
            break;
    }
    [self starSongs];
    [self stateMusic];
}

- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    if (second/3600 >= 1) {
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [[self dateFormatter] stringFromDate:d];
    return showtimeNew;
}

- (NSDateFormatter *)dateFormatter {
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}
//上一首
- (IBAction)previousMusic:(id)sender {
   
    [self removeSave];
   self.currentIndex--;
      if (self.currentIndex <= -1) {
        self.currentIndex = (int)self.songsArray.count - 1;
   }
    [self starSongs];
    [self stateMusic];
    
}
//下一首
- (IBAction)nextMusic:(id)sender {
   
    [self removeSave];
    self.currentIndex++;
    if (self.currentIndex >= (int)self.songsArray.count) {
        self.currentIndex = 0;
    }
    [self starSongs];
    [self stateMusic];
    
}
//播放模式
- (IBAction)playModel:(UIButton *)sender {
    self.playModel++;
    
    switch (self.playModel) {
        case 0:
            [sender setImage:[UIImage imageNamed:@"顺序"] forState:UIControlStateNormal];
            break;
        case 1:
             [sender setImage:[UIImage imageNamed:@"随机"] forState:UIControlStateNormal];
            break;
        case 2:
            [sender setImage:[UIImage imageNamed:@"单曲循环"] forState:UIControlStateNormal];
            self.playModel = 0;
            break;
    }
}

- (IBAction)collectMusic:(id)sender {
    
    
}
- (IBAction)downMusic:(id)sender {
    
    
}
- (IBAction)settingMusic:(id)sender {
}
- (IBAction)backClick:(id)sender {
    
    
    int number = (int)self.currentIndex;
    // 刷新前面的页面
    if (self.refreshblock) {
        self.refreshblock(number);
    }

    [self dismissViewControllerAnimated:YES completion:nil];
    
//    YXMUsicListViewController *musicLixtViewContro = [self.storyboard instantiateViewControllerWithIdentifier:@"musicList"];
//    self.view.window.rootViewController = musicLixtViewContro;
}
- (IBAction)shareMusic:(id)sender {
}

-(void)removeSave{
    [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    [self.playerView.player removeTimeObserver:self.playbackTimeObserver];
    
    self.timeLabel.text = [NSString stringWithFormat:@"00:00"];
    self.currentTimeLabel.text = [NSString stringWithFormat:@"00:00"];
}

- (void)dealloc {
   [self removeSave];
    NSLog(@"dealloc");
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
